package com.newworld.dmsapp2.activity.serviceapply;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.OutputStream;
import java.lang.ref.WeakReference;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;

import android.annotation.SuppressLint;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.ActivityInfo;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.graphics.Bitmap.CompressFormat;
import android.graphics.PointF;
import android.graphics.drawable.BitmapDrawable;
import android.media.ExifInterface;
import android.net.Uri;
import android.os.Bundle;
import android.os.Environment;
import android.provider.MediaStore;
import android.util.Log;
import android.view.Display;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.Window;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.newworld.dmsapp2.R;
import com.newworld.dmsapp2.bean.User;
import com.newworld.dmsapp2.util.Config;
import com.newworld.dmsapp2.util.SingleSample;
import com.newworld.dmsapp2.util.SysApplication;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.assist.ImageScaleType;
import com.nostra13.universalimageloader.core.assist.ImageSize;
import com.nostra13.universalimageloader.core.listener.SimpleImageLoadingListener;

@SuppressLint({ "SdCardPath", "NewApi" })
public class ChoosephotoActivity extends Activity implements OnClickListener {
	private static final int CHOOSEPICTURE_REQUESTCODE = 0;
	private static final String TAG = "choosephoto";
	private int flag = 0;
	private String image_path = "";
	// 顯示圖片的組件。
	private WeakReference<ImageView> imageView;

	Display currentDisplay;
	int dw;
	int dh;

	private Button zoomBtn, paintBtn, textBtn;

	static final int NONE = 0;
	static final int DRAG = 1;
	static final int ZOOM = 2;
	int mode = NONE;
	PointF start = new PointF();
	PointF mid = new PointF();
	float oldDist = 1f;
	private String paintPath = "";
	private String paintName = "";
	Context context;
	private Intent in;
	private LinearLayout backLayout, rightLayout;
	private String currentTime = "";
	public static String currentTimeString = "";
	private Button clearBtn;

	public static int ORIMAGE_WIDTH = 0;

	public static int ORIMAGE_HEIGHT = 0;
	public static int flag1 = 1;
	private PhotoViewAttacher1 mAttacher;
	private Uri uri;
	private Bundle bundle;
	private TextView titleTv;
	private TextView rightTextTv;

	public static final DisplayImageOptions options = new DisplayImageOptions.Builder()
			.cacheInMemory(false) // 设置下载的图片是否缓存在内存中
			.cacheOnDisk(false) // 设置下载的图片是否缓存在SD卡中
			.imageScaleType(ImageScaleType.EXACTLY) // default
			.bitmapConfig(Bitmap.Config.RGB_565).build();

	@SuppressWarnings("deprecation")
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.e(TAG, "onCreate");
		requestWindowFeature(Window.FEATURE_NO_TITLE);
		setContentView(R.layout.activity_choose_photo);
		SysApplication.getInstance().addActivity(this);
		setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
		titleTv = (TextView) findViewById(R.id.titlebar_both_center_title);
		backLayout = (LinearLayout) findViewById(R.id.titlebar_both_left_layout);
		rightLayout = (LinearLayout) findViewById(R.id.titlebar_both_right_layout);
		rightTextTv = (TextView) findViewById(R.id.titlebar_both_right_text);
		titleTv.setText("添加缺陷照片");
		rightTextTv.setText("保存");
		currentDisplay = getWindowManager().getDefaultDisplay();
		dw = currentDisplay.getWidth();
		dh = currentDisplay.getHeight();
		if (dw > 500) {
			dw = 500;
		}
		if (dh > 500) {
			dh = 500;
		}
		// 獲取潔面xml文件相關的View對象
		imageView = new WeakReference<ImageView>(
				(ImageView) findViewById(R.id.iv_picture));
		zoomBtn = (Button) findViewById(R.id.btn_zoom);
		paintBtn = (Button) findViewById(R.id.btn_paint);
		textBtn = (Button) findViewById(R.id.btn_text);
		clearBtn = (Button) findViewById(R.id.btn_clear);
		// zoomBtn.setBackgroundColor(getResources().getColor(R.drawable.button_white));
		// zoomBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
		// paintBtn.setBackgroundColor(getResources().getColor(R.drawable.button_red));
		// paintBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
		// textBtn.setBackgroundColor(getResources().getColor(R.drawable.button_red));
		// textBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
		clearBtn.setOnClickListener(this);
		flag = WritePaperActivity.flag;

		zoomBtn.setOnClickListener(this);
		paintBtn.setOnClickListener(this);
		textBtn.setOnClickListener(this);
		// 給ImageView對象設置onTouch監聽,該類實現了android.view.View.OnTouchListener接口
		/* imageView.setOnTouchListener(this); */
		// 該開始，設置saveButton為不可用狀態

		context = this;
		in = getIntent();
		bundle = in.getExtras();
		image_path = bundle.getString("imagePath");

		if (null != image_path && !image_path.equals("")) {
			File file = new File(image_path);
			uri = Uri.fromFile(file);
			sendBroadcast(new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE, uri));
		}

		if (null != image_path && !image_path.equals("") && flag == 1) {
			try {
				System.out.println("1111111111111def");
				SimpleDateFormat df2 = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Calendar date = Calendar.getInstance();
				date.setTimeInMillis(System.currentTimeMillis());
				currentTimeString = df2.format(date.getTime());
			} catch (Exception ee) {

			}
		}
		if (null != image_path && !image_path.equals("") && flag == 2) {
			try {
				ExifInterface exif = new ExifInterface(image_path);
				currentTime = exif.getAttribute(ExifInterface.TAG_DATETIME);
				SimpleDateFormat df = new SimpleDateFormat(
						"yyyy:MM:dd HH:mm:ss");
				SimpleDateFormat df1 = new SimpleDateFormat(
						"yyyy-MM-dd HH:mm:ss");
				Date today = df.parse(currentTime);
				currentTimeString = df1.format(today);
			} catch (Exception ee) {

			}

		}
		if (null == currentTime) {

			Toast.makeText(this, "图片信息不全，请另选图片！", Toast.LENGTH_SHORT).show();
			flag = 2;
			Intent i = new Intent(
					Intent.ACTION_PICK,
					android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
			/*
			 * Intent choosePictureIntent=new
			 * Intent(Intent.ACTION_GET_CONTENT);//ACTION_OPEN_DOCUMENT
			 * choosePictureIntent.addCategory(Intent.CATEGORY_OPENABLE);
			 */
			i.setType("image/jpeg");

			if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
				startActivityForResult(i, CHOOSEPICTURE_REQUESTCODE);
			} else {
				startActivityForResult(i, CHOOSEPICTURE_REQUESTCODE);
			}

		} else {

			ImageSize mImageSize = new ImageSize(dw, dh);
			ImageLoader.getInstance().loadImage("file://" + image_path,
					mImageSize, options, new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							try {
								ORIMAGE_WIDTH = loadedImage.getWidth();
								ORIMAGE_HEIGHT = loadedImage.getHeight();
								imageView.get().setImageBitmap(loadedImage);
								mAttacher = new PhotoViewAttacher1(imageView);
							} catch (IllegalStateException e) {
								Toast.makeText(ChoosephotoActivity.this,
										"IllegalStateException，请另选图片！",
										Toast.LENGTH_SHORT).show();
								flag = 2;
								Intent i = new Intent(
										Intent.ACTION_PICK,
										android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

								i.setType("image/jpeg");

								if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
									startActivityForResult(i,
											CHOOSEPICTURE_REQUESTCODE);
								} else {
									startActivityForResult(i,
											CHOOSEPICTURE_REQUESTCODE);
								}
							} catch (OutOfMemoryError e) {
								e.printStackTrace();
							} finally {
								loadedImage = null;
							}

						}
					});

			zoomBtn.setEnabled(true);
			paintBtn.setEnabled(true);
			textBtn.setEnabled(true);
			clearBtn.setEnabled(true);
		}

		rightLayout.setOnClickListener(new OnClickListener() {

			@Override
			public void onClick(View v) {

				if (null != imageView && null != imageView.get()) {
					BitmapDrawable bitmapDrawable = ((BitmapDrawable) imageView
							.get().getDrawable());
					if (bitmapDrawable != null) {
						Bitmap bitmap = bitmapDrawable.getBitmap();
						User user = SingleSample.getInstance(
								ChoosephotoActivity.this).getUser();
						long time = System.currentTimeMillis();
						SimpleDateFormat format = new SimpleDateFormat(
								"yyyyMMddHHmmssS");
						Date date = new Date(time);
						String dateString = format.format(date);
						/*
						 * paintName = user.getUsername() + "_" + dateString +
						 * ".jpg";
						 */
						paintName = user.getUsername() + dateString + ".jpg";
						paintPath = Config.IMAGE_PATH + File.separator
								+ paintName;
						File file = new File(paintPath);

						Uri imageFileUri = Uri.fromFile(file);
						try {
							OutputStream imageFileOS = getContentResolver()
									.openOutputStream(imageFileUri);
							// compress方法，压缩成jpg格式，0-100代表了压缩质量 100质量最好
							// 第三个参数把压缩图片写到输出流
							bitmap.compress(CompressFormat.JPEG, 80,
									imageFileOS);
							// 保存成功，进行提示
							Toast.makeText(context, "保存图片成功", Toast.LENGTH_LONG)
									.show();

							if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
								new SingleMediaScanner(context, file);
							} else {
								sendBroadcast(new Intent(
										Intent.ACTION_MEDIA_MOUNTED,
										Uri.parse("file://"
												+ Environment
														.getExternalStorageDirectory())));
							}

							bundle.putString("imagePath", paintName);
							in.putExtras(bundle);
							flag1 = 1;
							System.out.println("tuya_path" + paintPath);

							setResult(Activity.RESULT_OK, in);

							try {
								bitmap = null;
								bitmapDrawable = null;
								imageFileOS.close();
							} catch (IOException e) {
								// TODO 自动生成的 catch 块
								e.printStackTrace();
							}
							clean();
							finish();
							System.gc();

						} catch (FileNotFoundException e) {
							e.printStackTrace();
						}
					}
				} else {
					Toast.makeText(context, "请选择照片", Toast.LENGTH_SHORT).show();
				}
			}
		});

		backLayout.setOnClickListener(new OnClickListener() {
			@Override
			public void onClick(View v) {
				new AlertDialog.Builder(ChoosephotoActivity.this)
						.setTitle("退出添加图片")
						.setMessage("图片没有保存,确定退出编辑吗？")
						.setPositiveButton(
								"是",
								new android.content.DialogInterface.OnClickListener() {
									@Override
									public void onClick(DialogInterface arg0,
											int arg1) {
										clean();
										ChoosephotoActivity.this.finish();
										System.gc();
									}
								}).setNegativeButton("否", null).create().show();

			}
		});
	}

	@Override
	public void onClick(View v) {

		// 因為給不同的Button對象都設置了onClick監聽，所以需要判斷觸發的是哪個Button的監聽事件
		switch (v.getId()) {

		case R.id.btn_zoom:

			flag1 = 1;
			zoomBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_red));
			zoomBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			// paintBtn.setBackgroundColor(getResources().getColor(R.color.nw_bg_white));
			textBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			textBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// zoomBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			paintBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			paintBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// textBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			break;
		case R.id.btn_paint:

			flag1 = 2;
			zoomBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			zoomBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// paintBtn.setBackgroundColor(getResources().getColor(R.color.nw_bg_white));
			textBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			textBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// zoomBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			paintBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_red));
			paintBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			// textBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			break;
		case R.id.btn_text:

			flag1 = 0;
			zoomBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			zoomBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// paintBtn.setBackgroundColor(getResources().getColor(R.color.nw_bg_white));
			textBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_red));
			textBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			// zoomBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			paintBtn.setBackground(getResources().getDrawable(
					R.drawable.photo_white));
			paintBtn.setTextColor(getResources().getColor(R.color.nw_bt_red));
			// textBtn.setTextColor(getResources().getColor(R.color.nw_bg_white));
			break;
		case R.id.btn_clear:

			imageView.get().setImageDrawable(null);
			imageView.get().setImageBitmap(null);
			Log.e(TAG, "dw=" + dw + ",dh=" + dh);
			ImageSize mImageSize = new ImageSize(dw, dh);
			ImageLoader.getInstance().loadImage("file://" + image_path,
					mImageSize, options, new SimpleImageLoadingListener() {
						@Override
						public void onLoadingComplete(String imageUri,
								View view, Bitmap loadedImage) {
							super.onLoadingComplete(imageUri, view, loadedImage);
							try {

								ORIMAGE_WIDTH = loadedImage.getWidth();
								ORIMAGE_HEIGHT = loadedImage.getHeight();
								imageView.get().setImageBitmap(loadedImage);
								mAttacher.setCavus(imageView.get());
							} catch (IllegalStateException e) {
								Toast.makeText(ChoosephotoActivity.this,
										"IllegalStateException，请另选图片！",
										Toast.LENGTH_SHORT).show();
								flag = 2;
								Intent i = new Intent(
										Intent.ACTION_PICK,
										android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

								i.setType("image/jpeg");

								if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
									startActivityForResult(i,
											CHOOSEPICTURE_REQUESTCODE);
								} else {
									startActivityForResult(i,
											CHOOSEPICTURE_REQUESTCODE);
								}
							} catch (OutOfMemoryError e) {
								e.printStackTrace();
							} finally {
								loadedImage = null;
							}
						}
					});

			break;

		}

	}

	@SuppressLint("SdCardPath")
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {

		Uri uri = null;
		Log.e(TAG + "_onActivityResult", "requestCode=" + requestCode
				+ ",resultCode=" + resultCode);

		// 判斷返回是否OK
		if (resultCode == RESULT_OK) {
			Log.e(TAG + "_onActivityResult", "resultCode == RESULT_OK");
			String sdStatus = Environment.getExternalStorageState();
			if (!sdStatus.equals(Environment.MEDIA_MOUNTED)) {
				System.out.println("sd否可用");// 检测sd是否可用
				Log.e(TAG + "_onActivityResult",
						"SD card is not avaiable/writeable right now.");
				return;
			}
			if (requestCode == 0) {
				Log.e(TAG + "_onActivityResult", "1111111111111140");
				uri = data.getData();
				String[] filePathColumn = { MediaStore.Images.Media.DATA };
				Log.e("picture", uri.toString());
				Cursor cursor = getContentResolver().query(uri, filePathColumn,
						null, null, null);
				cursor.moveToFirst();

				int columnIndex = cursor.getColumnIndex(filePathColumn[0]);
				image_path = cursor.getString(columnIndex);
				cursor.close();
				Log.e(TAG + "_onActivityResult", "11111111111====>"
						+ image_path);
			}

			try {
				// Log.e("uri",uri.toString());
				if (null == getContentResolver().openInputStream(uri)
						|| null == uri) {

					Intent choosePictureIntent = new Intent(
							Intent.ACTION_PICK,
							android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
					choosePictureIntent.setType("image/jpeg");

					if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.BASE) {
						startActivityForResult(choosePictureIntent,
								CHOOSEPICTURE_REQUESTCODE);
					} else {
						startActivityForResult(choosePictureIntent,
								CHOOSEPICTURE_REQUESTCODE);
					}
				}
			} catch (Exception e1) {
				// TODO Auto-generated catch block
				e1.printStackTrace();
				Log.e(TAG + "_onActivityResult" + "photo_e1", e1.getMessage());
				System.exit(1);
			}

			Log.e(TAG + "_onActivityResult", "flag = " + flag);
			if (requestCode == 0 || flag == 2) {
				try {
					SimpleDateFormat df2 = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					Calendar date = Calendar.getInstance();
					date.setTimeInMillis(System.currentTimeMillis());
					currentTimeString = df2.format(date.getTime());
					ExifInterface exif = new ExifInterface(image_path);
					currentTime = exif.getAttribute(ExifInterface.TAG_DATETIME);
					SimpleDateFormat df = new SimpleDateFormat(
							"yyyy:MM:dd HH:mm:ss");
					SimpleDateFormat df1 = new SimpleDateFormat(
							"yyyy-MM-dd HH:mm:ss");
					Date today = df.parse(currentTime);
					currentTimeString = df1.format(today);
					Log.e(TAG + "_onActivityResult", "currentTime:"
							+ currentTimeString);
				} catch (Exception ee) {

				}

			}

			if (null == currentTime) {

				Toast.makeText(this, "图片信息不全，请另选图片！", 1).show();
				flag = 2;
				Intent i = new Intent(
						Intent.ACTION_PICK,
						android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

				i.setType("image/jpeg");

				if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
					startActivityForResult(i, CHOOSEPICTURE_REQUESTCODE);
				} else {
					startActivityForResult(i, CHOOSEPICTURE_REQUESTCODE);
				}
			} else {

				Log.e(TAG + "_onActivityResult", "1111111111111121");
				imageView.get().setImageBitmap(null);

				Log.e(TAG + "_onActivityResult", "this.dw=" + this.dw
						+ ",this.dh=" + this.dh);
				ImageSize mImageSize = new ImageSize(dw, dh);
				ImageLoader.getInstance().loadImage("file://" + image_path,
						mImageSize, options, new SimpleImageLoadingListener() {
							@Override
							public void onLoadingComplete(String imageUri,
									View view, Bitmap loadedImage) {
								super.onLoadingComplete(imageUri, view,
										loadedImage);
								try {
									/*
									 * setIpMessageBitmapCache(loadedImage.copy(
									 * Config.RGB_565, true));
									 */
									ORIMAGE_WIDTH = loadedImage.getWidth();
									ORIMAGE_HEIGHT = loadedImage.getHeight();
									imageView.get().setImageBitmap(loadedImage);
									if (null == mAttacher) {
										mAttacher = new PhotoViewAttacher1(
												imageView);
									} else {
										mAttacher.setCavus(imageView.get());
									}
								} catch (IllegalStateException e) {
									Toast.makeText(ChoosephotoActivity.this,
											"IllegalStateException，请另选图片！",
											Toast.LENGTH_SHORT).show();
									flag = 2;
									Intent i = new Intent(
											Intent.ACTION_PICK,
											android.provider.MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

									i.setType("image/jpeg");

									if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
										startActivityForResult(i,
												CHOOSEPICTURE_REQUESTCODE);
									} else {
										startActivityForResult(i,
												CHOOSEPICTURE_REQUESTCODE);
									}
								} catch (OutOfMemoryError e) {
									e.printStackTrace();
								} finally {
									loadedImage = null;
								}
							}
						});
				zoomBtn.setEnabled(true);
				paintBtn.setEnabled(true);
				textBtn.setEnabled(true);
				clearBtn.setEnabled(true);
			}
		} else if (resultCode == Activity.RESULT_CANCELED) {
			System.out.println("111111111ghk");
			clean();
			finish();
			System.gc();
			return;
		}
		super.onActivityResult(requestCode, resultCode, data);
	}

	protected void clean() {
		Log.e(TAG, "clean");
		try {
			if (null != mAttacher)
				mAttacher.cleanup();

			if (null != imageView || imageView.get() != null) {
				ImageLoader.getInstance().cancelDisplayTask(imageView.get());
				imageView.get().setImageDrawable(null);
				imageView.get().setImageBitmap(null);
				imageView = null;
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	@Override
	public void onBackPressed() {
		new AlertDialog.Builder(ChoosephotoActivity.this)
				.setTitle("退出添加图片")
				.setMessage("图片没有保存,确定退出编辑吗？")
				.setPositiveButton("是",
						new android.content.DialogInterface.OnClickListener() {
							@Override
							public void onClick(DialogInterface arg0, int arg1) {
								clean();
								ChoosephotoActivity.this.finish();
								System.gc();
							}
						}).setNegativeButton("否", null).create().show();
		super.onBackPressed();
	}

}
